package org.xiaoken.wechat.robot.message.impl;

import com.alibaba.fastjson.JSONObject;
import org.xiaoken.wechat.robot.message.Message;
import org.xiaoken.wechat.robot.message.MessageException;
import org.xiaoken.wechat.robot.message.Sender;
import org.xiaoken.wechat.robot.util.MessageSendUtil;

import java.io.IOException;
import java.util.Objects;

/**
 * @program: wechat-robot-starter
 * @description: 通用常见的消息发送者
 * @author: guokenye
 **/
public class GenericSender implements Sender {

    protected static final String ERRCODE_KEY = "errcode";
    protected static final String ERRMSG_KEY = "errmsg";
    protected static final Integer SUCCESS_CODE = 0;

    private String name;
    private String webhook;
    private Integer socketTimeout;
    private Integer connectTimeout;

    public GenericSender(String name, String webhook, Integer socketTimeout, Integer connectTimeout) {
        this.name = name;
        this.webhook = webhook;
        this.socketTimeout = socketTimeout;
        this.connectTimeout = connectTimeout;
    }


    public String getName() {
        return name;
    }

    public String getWebhook() {
        return webhook;
    }

    public Integer getSocketTimeout() {
        return socketTimeout;
    }

    public Integer getConnectTimeout() {
        return connectTimeout;
    }

    @Override
    public void send(Message message) throws IOException, MessageException {
        String resultStr = MessageSendUtil.send(message, this.webhook, this.socketTimeout, this.connectTimeout);
        JSONObject json = JSONObject.parseObject(resultStr);
        Integer errCode = json.getInteger(ERRCODE_KEY);
        if (!Objects.equals(SUCCESS_CODE, errCode)) {
            throw new MessageException(errCode, json.getString(ERRMSG_KEY));
        }
    }
}
